﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace XmlDatabase.Core
{
    internal class XIdsManager
    {
        private static Dictionary<String , XIdsManager> instances = new Dictionary<String , XIdsManager>();
        private Dictionary<Object, Guid> ids = new Dictionary<Object, Guid>();
        private XIdsManager() { }

        public static XIdsManager GetInstance(String db)
        {
            if (!XIdsManager.instances.Keys.Contains(db))
            {
                XIdsManager.instances.Add(db, new XIdsManager());
            }
            return XIdsManager.instances[db];
        }
        public Guid GetObjectId(Object o)
        {
            if (this.ids.Keys.Contains(o))
            {
                return ids[o];
            }
            else
            {
                return Guid.Empty;
            }
        }
        public void Set(Object o, Guid id)
        {
            if (this.ids.Values.Contains(id))
            {
                this.ids.Remove(this.ids.FirstOrDefault((k) => k.Value == id).Value);
                this.Set(o, id);
            }
            else
            {
                if (this.ids.Keys.Contains(o))
                {
                    return;
                }
                else
                {
                    this.ids.Add(o, id);
                }
            }
        }
        public void Remove(Object o)
        {
            this.ids.Remove(o);
        }
        public void Clear()
        {
            this.ids.Clear();
        }
    }
}
